package kgame5.k3d.core.view3d {
import kgame5.k3d.core.camera.Camera3D;
import kgame5.k3d.core.math.Matrix3D;
import kgame5.k3d.core.math.Vector3D;
import kgame5.k3d.util3d.intersection.RayTest;

import flash.utils.getTimer;

/**
 * @author kk
 * 做成Node3D也可以，这里只是作为工具而使用
 */
public class Mouse3D {
	
	public static const PRICISION:int=4;//鼠标移动在这个范围之外，则认为是没有移动，减低计算量
	
	public static var Mouse3DX:Number;
	public static var Mouse3DZ:Number;
	
	
	public function Mouse3D():void{
	}

	//=========================================================
	//额外的功能，提供鼠标到3d世界xoz平面的映射
	private var Mcw:Matrix3D=new Matrix3D();
	private var
		preMouseX:int=-9999,
		preMouseY:int=-9999;
	
	
	public function update(mouseX:int,mouseY:int,camera:Camera3D):void{
//		//var t:int=getTimer();
		if(Math.abs(mouseX-preMouseX)<PRICISION
			&&Math.abs(mouseY-preMouseY)<PRICISION){
			
			//!!这里是不能设置的，如果设置了，则数据始终不是真实的了
			//preMouseX=mouseX;
			//preMouseY=mouseY;
			//trace("--"+(getTimer()-t)+"ms");
			return;
		}else{
			preMouseX=mouseX;
			preMouseY=mouseY;
		}
		
//		//line
		Matrix3D.SInverse(camera.Mwc, Mcw);//求逆矩阵
		var lineP0:Vector3D=new Vector3D();
		lineP0.fill(0, 0, 0);
		var lineP1:Vector3D=new Vector3D(mouseX,-mouseY,View3D.D);
//
//		//lineD转化到世界坐标
		Matrix3D.SMul_VM(lineP0.clone(), Mcw, lineP0);
		Matrix3D.SMul_VM(lineP1.clone(), Mcw, lineP1);
		lineP1.sub(lineP0);
		var lineD:Vector3D=lineP1;
		//trace(lineP0,lineD);
//		
//		//--plane
		var planeN:Vector3D=new Vector3D(0,1,0);
		var planeD:Number=0;
		
		var mouse3D:Vector3D= RayTest.test(lineP0, lineD, planeN, planeD);
//		
		Mouse3DX=mouse3D.x;
		Mouse3DZ=mouse3D.z;
		
		//trace((getTimer()-t)+"ms");
	}
}
}
